<template>
  <div :class="`tw-libinput x${_uid}`">
    <label v-if="title"
      class="tw-libinput-label"
      :style="{width: labelWidth}">{{title}}:</label>
    <div class="tw-libinput-data" v-if="filterable">
      <el-autocomplete
        :class="{xerror: errText}"
        v-model="val"
        :fetch-suggestions="querySearch"
        :placeholder="placeholder"
        :type="texttype"
        :maxlength="maxlength"
        :minlength="minlength"
        :clearable="clearable"
        :autosize="autosize"
        :size="size"
        :disabled="valdisabled"
        :rows="rows"
        :autofocus="autofocus"
        :show-word-limit="showWordLimit"
        @change="changeValue"
        @select="handleSelect"
      >
        <template slot="prepend" v-if="prependval">{{prependval}}</template>
        <template slot="append" v-if="appendval">{{appendval}}</template>
        <i slot="prefix" :class="prefixcls" v-if="prefixcls"></i>
        <i slot="suffix" :class="suffixcls" v-if="suffixcls"></i>
      </el-autocomplete>

      <div v-if="validValue && errText" class="tw-validinput-err">{{errText}}</div>
    </div>
    <div class="tw-libinput-data" v-else>
      <el-input :class="{xerror: errText}"
        :placeholder="placeholder"
        :type="texttype"
        :maxlength="maxlength"
        :minlength="minlength"
        :clearable="clearable"
        :autosize="autosize"
        :size="size"
        :show-password="showPassword"
        :autocomplete="autocomplete"
        :disabled="valdisabled"
        :rows="rows"
        :autofocus="autofocus"
        :show-word-limit="showWordLimit"
        @change="changeValue"
        @blur="blurValue"
        v-model="val">
        <template slot="prepend" v-if="prependval">{{prependval}}</template>
        <template slot="append" v-if="appendval">{{appendval}}</template>
        <i slot="prefix" :class="prefixcls" v-if="prefixcls"></i>
        <i slot="suffix" :class="suffixcls" v-if="suffixcls"></i>
      </el-input>

      <div v-if="validValue && errText" class="tw-validinput-err">{{errText}}</div>
    </div>
  </div>
</template>

<script>
import props from './props'

export default {
  name: 'libinput',

  props,

  data() {
    return {
      val: '',
      valdisabled: false,
      errText: ''
    }
  },

  methods: {
    blurValue () {
      this.validData('blur')
    },
    changeValue () {
      if (this.validData('change')) {
        this.$emit('input', this.val)
        this.$emit('change', this.val)
      }
    },
    validData (now) {
      let vm = this
      let errText = ''

      if (this.validValue && this.validRules.length > 0) {
        this.validRules.forEach((itm) => {
          let trigger = itm.trigger || 'blur'
          if (now === trigger) {
            if (itm.required !== undefined && itm.required && !vm.val) {
              errText = itm.message
            }

            if (!errText && itm.min !== undefined && vm.val.length < parseInt(itm.min)) {
              errText = itm.message
            }
            if (!errText && itm.max !== undefined && vm.val.length > parseInt(itm.max)) {
              errText = itm.message
            }
            if (!errText && itm.pattern !== undefined && !eval(itm.pattern).test(vm.val)) {
              errText = itm.message
            }

            if (!errText && itm.validator !== undefined && itm.validator) {
              errText = vm.custValidFunc(itm)
            }
          }
        })
      }

      vm.errText = errText
      return !errText
    },
    custValidFunc (itm) {
      let errText = ''
      if (this.validFunc !== '' && typeof this.validFunc === 'function') {
        errText = this.validFunc(this.val)
      }

      return errText
    },

    setStyle () {
      let style = `.x${this._uid}
        .el-input .el-input__inner {
          color: ${this.color};
          background-color: ${this.bgColor};
          border-color: ${this.borderColor};
        }
        .x${this._uid} .el-input.is-active .el-input__inner, .x${this._uid} .el-input__inner:focus {
          border-color: ${this.focusBorderColor};
        }
        .x${this._uid} .tw-libinput-label {
          width: ${this.labelWidth};
          line-height: ${this.titleHeight};
          font-weight: ${this.titleWeight};
        }
      `
      if (this.filterable) {
        style = `
          .x${this._uid} .el-input .el-input__inner {
            color: ${this.color};
            background-color: ${this.bgColor};
            border-color: ${this.borderColor};
          }
          .x${this._uid} .el-input.is-active .el-input__inner, .x${this._uid} .el-input__inner:focus {
            border-color: ${this.focusBorderColor};
          }

          .x${this._uid} .tw-libinput-label {
            width: ${this.labelWidth};
            line-height: ${this.titleHeight};
            font-weight: ${this.titleWeight};
          }
        `
      }

      if (this.validValue) {
        style += `
          .x${this._uid} .tw-libinput-label::before {
            content: "*";
            color: #f56c6c;
            margin-right: 4px;
          }

          .x${this._uid} .el-input.xerror .el-input__inner {
            border-color: #f56c6c;
          }
        `
      }

      const styleEl = document.getElementById(this._uid) || document.createElement('style')
      styleEl.id = this._uid
      styleEl.innerText = style.replace(/\n/g, '')

      document.head.appendChild(styleEl)
    },

    // setValFromDefault () {
    //   this.val = this.default
    //   this.changeValue()
    // },

    // init (reset) {
    //   const initValue = this.value === true ? '' : this.value

    //   if ([undefined, ''].includes(initValue) || reset) {
    //     if (this.default) {
    //       this.setValFromDefault()
    //     } else if (this.selectedFirst && this.options.length > 0) {
    //       this.val = this.multiple ? [this.options[0].value] : this.options[0].value
    //       this.changeValue()
    //     } else {
    //       this.val = this.multiple ? [] : ''
    //     }
    //   } else {
    //     this.val = initValue
    //   }
    // },
    querySearch (queryString, cb) {
      let restaurants = this.list
      let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter (queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    handleSelect(item) {
      this.$emit('input', this.val)
      this.$emit('change', this.val)
    },
    disValue () {
      this.valdisabled = this.disabled
      if (this.validRules.length > 0) {
        this.validRules.forEach((itm) => {
          if (itm.disabled !== undefined && itm.disabled) {
            this.valdisabled = itm.disabled
          }
        })
      }
    }
  },

  computed: {
    style () {
      return {
        color: this.color,
        bgColor: this.bgColor,
        borderColor: this.borderColor,
        focusBorderColor: this.focusBorderColor
      }
    }
  },

  mounted () {
    this.val = this.value
    this.setStyle()
    this.disValue()
  },

  watch: {
    value () {
      this.val = this.value
    },
    validRules: {
      deep: true,
      handler () {
        this.disValue()
      }
    },

    style: {
      deep: true,
      handler () {
        this.setStyle()
      }
    }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
